package com.clei.dto.db;

import com.clei.enums.DatabaseServerEnum;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 表信息
 *
 * @author Y
 * @date 2024-01-09
 **/
public class TableInfo {

    /**
     * 表名
     */
    private final String tableName;

    /**
     * 建表sql
     */
    private final String createSql;

    /**
     * insertPrefix
     * INSERT INTO tableName(a,b,c,d)
     */
    private final String insertPrefix;

    /**
     * insertValues
     * (a,b,c,d)
     */
    private final String insertValues;

    /**
     * 列
     */
    private final List<ColumnProperty> columnList;

    public TableInfo(DatabaseServerEnum dbServer, String tableName, String createSql, List<ColumnProperty> columnList) {
        this.tableName = tableName;
        this.createSql = createSql;
        this.columnList = columnList;
        this.insertPrefix = getInsertPrefix(dbServer);
        this.insertValues = '(' + columnList.stream().map(p -> "%s").collect(Collectors.joining(", ")) + ')';
    }

    public String getTableName() {
        return tableName;
    }

    public String getCreateSql() {
        return createSql;
    }

    public List<ColumnProperty> getColumnList() {
        return columnList;
    }

    public String getInsertPrefix() {
        return insertPrefix;
    }

    public String getInsertPrefix(DatabaseServerEnum dbServer) {
        // 表名加上反引号 今天刚遇到一个表名带中划线导致导入失败的
        String res;
        switch (dbServer) {
            case MYSQL:
                res = "INSERT INTO `%s`\n("
                        + columnList.stream().map(ColumnProperty::getColumnName).collect(Collectors.joining(", "))
                        + ")\nVALUES";
                break;
            case TAOS:
                res = "INSERT INTO `%s` ("
                        + columnList.stream().map(ColumnProperty::getColumnName).collect(Collectors.joining(", "))
                        + ") VALUES ";
                break;
            default:
                res = null;
        }
        return res;
    }

    public String getInsertValues() {
        return insertValues;
    }
}
